# coding:utf-8
import os,re,json
import requests,shutil
from hashlib import md5
import numpy as np


def fen_test_sample():
    img_dir = r'./train/img'
    txt_dir = r'./train/gt'
    # 分配比列 5分之1
    test_total = len(os.listdir(img_dir)) * 0.1
    print('测试样本：{0}'.format(test_total))

    test_img_dir = r'./test/img'
    test_txt_dir = r'./test/gt'
    if not os.path.exists(test_img_dir):
        os.makedirs(test_img_dir)
    if not os.path.exists(test_txt_dir):
        os.makedirs(test_txt_dir)
    img_list = os.listdir(img_dir)
    txt_list = os.listdir(txt_dir)
    divide = len(img_list) // test_total + 1
    for n, i in enumerate(img_list):
        if n % divide == 0:
            if '.jpg' in i:
                temp = re.findall(r'(.*?)\.jpg', i)
                if temp[0] + '.txt' not in txt_list:
                    print(i)
                    break
                else:
                    img_path = os.path.join(img_dir, i)
                    txt_path = os.path.join(txt_dir, temp[0] + '.txt')
                    print(n, test_img_dir, "正在迁移...{0}".format(i))
                    shutil.move(img_path, test_img_dir)
                    shutil.move(txt_path, test_txt_dir)
    print('************end************')


def GetImgLabel():
    '''

    '''
    test_img_dir = r'./test/img'
    test_txt_dir = r'./test/gt'
    train_img_dir = r'./train/img'
    train_txt_dir = r'./train/gt'

    print('-------------处理 test-------------')
    test_txt_list = os.listdir(test_txt_dir)
    test_img_list = os.listdir(test_img_dir)
    print(f'读取 test_img：{len(test_img_list)}')
    print(f'读取 test_txt：{len(test_txt_list)}')
    num = 0
    with open('test.txt', 'w+') as f:
        for n, i in enumerate(test_img_list):
            if '.jpg' in i:
                temp = re.findall(r'(.*?)\.jpg', i)
                if temp[0] + '.txt' not in test_txt_list:
                    print(i)
                    break
                else:
                    num += 1
                    f.write(f'./datasets/test/img/{temp[0]}.jpg   	./datasets/test/gt/{temp[0]}.txt\n')
    print(f'共有处理 test：{num}')
    print('-------------处理 train-------------')
    train_txt_list = os.listdir(train_txt_dir)
    train_img_list = os.listdir(train_img_dir)
    print(f'读取 train_img：{len(train_img_list)}')
    print(f'读取 train_txt：{len(train_txt_list)}')
    num = 0
    with open('train.txt', 'w+') as f:
        for n, i in enumerate(os.listdir(train_img_dir)):
            if '.jpg' in i:
                temp = re.findall(r'(.*?)\.jpg', i)
                if temp[0] + '.txt' not in train_txt_list:
                    print(i)
                    break
                else:
                    num += 1
                    f.write(f'./datasets/train/img/{temp[0]}.jpg   	 ./datasets/train/gt/{temp[0]}.txt\n')
    print(f'共有处理 train：{num}')


def json2txt():
    dir_json = 'E:\python_code\JSZ_template\jsz_finish'
    dir_txt =os.path.join(dir_json, 'txt')
    if not os.path.exists(dir_txt):
        os.makedirs(dir_txt)
    list_json = os.listdir(dir_json)
    num = 0
    for cnt, json_name in enumerate(list_json):
        if json_name.endswith('.json'):
            num += 1
            print('cnt=%d, name=%s' % (cnt, json_name))
            path_json = os.path.join(dir_json, json_name)
            path_txt = os.path.join(dir_txt, json_name.replace('.json', '.txt'))

            with open(path_json, 'r', encoding='GBK') as path_json:
                jsonx = json.load(path_json)

            with open(path_txt, 'w+') as ftxt:
                for shape in jsonx['shapes']:
                    xy = np.array(shape['points'])
                    label = str(shape['label'])
                    strxy = ''
                    for m, n in xy:
                        strxy += str(m) + ',' + str(n) + ','
                    strxy += '0' + ',' + f'"{label}"'
                    ftxt.writelines(strxy + "\n")
    print(f'共有处理, json to txt：{num}')


if __name__ == '__main__':

    # fen_test_sample()
    GetImgLabel()
    # json2txt()